<template>
  <MainModule>
    <template #header>
      <el-row :gutter="16">
        <el-col :span="6">
          <el-form-item label="角色名称:">
            <MySelect v-model="table.param.RoleId" :options="rbac.RoleId" value="Value" label="Title"></MySelect>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="接口名称:">
            <el-input v-model="table.param.Name" placeholder="请输入" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="接口路径:">
            <el-input v-model="table.param.Path" placeholder="请输入" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-button type="success" @click="GetData">查询</el-button>
          <el-button type="warning" @click="Reset">重置</el-button>
          <el-button type="primary" @click="BindOrUnBind(1)">角色绑定全部API</el-button>
          <el-button type="danger" @click="BindOrUnBind(0)">角色解绑全部API</el-button>
        </el-col>
      </el-row>
    </template>

    <MyTable v-bind="MyTableData" :serial="(table.param.Page - 1) * table.param.PageSize + 1">
      <template #RoleIsEnable="{ row }">
        <el-switch v-model="row.RoleIsEnable" inline-prompt active-text="绑定" inactive-text="解绑"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          @change="RowBindOrUnBind(row)"></el-switch>
      </template>
      <template #operation="{ row }">
        <el-button type="primary" @click="Edit(row)">编辑</el-button>
        <el-button type="danger" @click="Delete(row)">删除</el-button>
      </template>
    </MyTable>
    <EditingDialog :fromParam="EditingParam" :param="table.param" :GetData="GetData"></EditingDialog>
    <BindingDialog :fromParam="BindingParam" :GetData="GetData"></BindingDialog>

    <template #footer>
      <MyPagination :total="table.total" v-model:currentPage="table.param.Page" v-model:pageSize="table.param.PageSize"
        @change="GetData"></MyPagination>
    </template>
  </MainModule>
</template>

<script lang="ts" setup>
import { MainModule, MyPagination, MySelect, MyTable, type MyTableType } from "@/components"
import { reactive, onMounted, onUnmounted } from 'vue';
import { RoleApiApiUrl, RoleApiApi } from '@/api/permession/bind'
import { PermessionApiUrl, PermessionApi } from '@/api/permession'
import { PermessionBind } from "./Def"
import { columns } from "./ConfigData"
import BindingDialog from "./BindingDialog.vue"
import EditingDialog from './EditingDialog.vue';
import { useMainLoading } from "@/hooks/useMainLoading"
import { AbortApi } from "@/library/utils/request";
import MessageUti from "@/library/utils/MessageUti"

const { openMainLoading, closeMainLoading } = useMainLoading()

const rbac = reactive<PermessionBind.rbacType>({
  AppId: [],
  App: [],
  RoleId: [],
})

const param = reactive<PermessionBind.ParamState>({
  RoleId: undefined,
  Name: "",
  Path: "",
  Page: 1,
  PageSize: 40
})

const table = reactive<PermessionBind.TableState>({
  param: { ...param },
  total: 0,
})

// 表格配置数据
const MyTableData = reactive<MyTableType>({
  loading: false,
  table: {
    data: []
  },
  columns
})

// EditingDialog 需要的数据
const EditingParam = reactive<PermessionBind.EditingDialog>({
  modal: false,
  row: null
})

const GetBaseParams = async () => {
  await PermessionApi.GetParams({}).then((res) => {
    rbac.AppId = res.Data.AppId
    rbac.App = res.Data.App
    rbac.RoleId = res.Data.RoleId
  })
}

const GetData = async () => {
  MyTableData.loading = true

  await RoleApiApi.SelectApiWithRole({ ...table.param }).then((res) => {
    res.Data.Data.forEach((item: any) => {
      item.RoleId = table.param.RoleId ? table.param.RoleId : undefined
      const Role = rbac.RoleId.find((Role: any) => Role.Value === table.param.RoleId)
      item.RoleName = Role ? Role.Title : ''
    });

    MyTableData.table.data = res.Data.Data
    table.total = res.Data.Count
    MyTableData.loading = false
  })
}

const Reset = () => {
  table.param = { ...param }
}

const Create = () => {
  EditingParam.modal = true
}

const Edit = (row: any) => {
  EditingParam.row = { ...row }
  EditingParam.modal = true
}

const Delete = async (row: any) => {
  const action = await MessageUti.confirm("删除API接口", `是否删除接口 ${row.Name}?`)
  if (!action) { return }

  RoleApiApi.DeleteApi({ Id: row.Id, AppId: row.AppId }).then((res) => {
    MessageUti.showSuccess('删除成功');
    table.param = { ...param }
    GetData();
  });
};

const RowBindOrUnBind = async (row: any) => {
  if (!row.RoleId) {
    await MessageUti.confirm("温馨提示", "需要选择角色查询后, 才能进行操作!", undefined, {
      confirmButtonText: "知道了",
      showCancelButton: false
    })
    row.RoleIsEnable = !row.RoleIsEnable;
  }
  else {
    let param = {
      RoleId: row.RoleId,
      ApiId: row.Id
    }
    const Api = row.RoleIsEnable ? RoleApiApi.AddApiToRole : RoleApiApi.DelApiFromRole

    Api({ ...param }).then(() => {
      MessageUti.showSuccess('操作成功')
      GetData()
    })
  }
}

// BindingDialog 需要的参数数据
const BindingParam = reactive<PermessionBind.BindingDialog>({
  modal: false,
  title: "",
  option: undefined,
  RoleId: rbac.RoleId
})

const BindOrUnBind = (option: number) => {
  BindingParam.RoleId = rbac.RoleId
  BindingParam.modal = true
  BindingParam.option = option
  BindingParam.title = option === 1 ? '角色绑定全部接口' : '角色解绑全部接口'
}

onMounted(async () => {
  openMainLoading()
  await GetData()
  await GetBaseParams()
  closeMainLoading()
})

onUnmounted(() => {
  AbortApi([RoleApiApiUrl.SelectApiWithRole, PermessionApiUrl.GetParams])
})

</script>

<style lang="scss" scoped></style>
